package com.test.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

public class MongoFactory {
	private String host;
	private int port;
	private int poolsize;
	private String dbName;
    private MongoClient mongoClient;
    private Map<String, MongoDatabase> dbPool = new ConcurrentHashMap<>();
    
	public MongoFactory(String host, int port, int poolsize, String dbName) {
		this.host = host;
		this.port = port;
		this.poolsize = poolsize;
		this.dbName = dbName;
		init();
	}

	public void init() {
		ServerAddress serverAddress = new ServerAddress(host, port);
    	MongoClientOptions mongoClientOptions = MongoClientOptions.builder()
    	.socketKeepAlive(true)
    	.maxConnectionIdleTime(200)
    	.minConnectionsPerHost(poolsize)
    	.connectionsPerHost(poolsize)
    	.build();    	
    	mongoClient = new MongoClient(serverAddress, mongoClientOptions);
    }
	
	public MongoDatabase getDb() {
    	return getDb(dbName);
    }
    
    private MongoDatabase getDb(String dbName) {
    	if(dbPool.containsKey(dbName)) {
    		return dbPool.get(dbName);
    	}
    	MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
    	dbPool.put(dbName, mongoDatabase);
    	return mongoDatabase;
    }

}
